package cn.liujianbo.springsecurity.service.impl;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 刘建波
 * @date 2022-04-22 21:40
 */
@Component
public class CustomUserDetailService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        String userName = username;
        String password = userName;
        // 查询角色
        List<String> rolesList = Arrays.asList("ROLE_USER", "ROLE_ADMIN");
        // 创建spring security 权限集合对象
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (String role : rolesList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(role));
        }

        // 返回spring security 用户对象
        return new User(username,password,grantedAuthorityList);
    }
}
